package com.pets.web.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.pets.web.entity.PetExpress;
import com.pets.web.entity.PetsDelivery;
import com.pets.web.entity.PetsOrders;
import com.pets.web.mapper.PetExpressMapper;
import com.pets.web.service.IPetExpressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pets.web.service.IPetOrdersService;
import com.pets.web.service.IPetsDeliveryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 物流信息表 服务实现类
 * </p>
 *
 * @author zhurenwang
 * @since 2024-05-29
 */
@Service
public class PetExpressServiceImpl extends ServiceImpl<PetExpressMapper, PetExpress> implements IPetExpressService {

    @Autowired
    private IPetsDeliveryService petsDeliveryService;
    @Autowired
    private IPetOrdersService petOrdersService;

    @Override
    public List<PetExpress> list(PetExpress petExpress) {
        return lambdaQuery()
                .eq(Objects.nonNull(petExpress.getDeliveryId()), PetExpress::getDeliveryId, petExpress.getDeliveryId())
                .orderByDesc(PetExpress::getStateTime).list();
    }

    @Override
    public List<PetExpress> detail(String orderNo) {
        List<PetExpress> petExpressList = new ArrayList<>();
        PetExpress first = new PetExpress();
        first.setState("待发货");
        first.setIntro("正在备货请耐心等待");
        PetsOrders orders = petOrdersService.selectByOrderNo(orderNo);
        if (Objects.isNull(orders)) {
            return Collections.emptyList();
        }
        first.setStateTime(orders.getCreateTime());
        petExpressList.add(first);
        List<PetsDelivery> petsDeliveryList = petsDeliveryService.selectByOrderId(orders.getId());
        if (petsDeliveryList.isEmpty()){
            return petExpressList;
        }
        PetsDelivery petsDelivery = petsDeliveryList.get(0);
        List<PetExpress> petExpresses = selectByDeliveryId(petsDelivery.getId());
        petExpressList.addAll(petExpresses);
        return petExpressList.stream().sorted(Comparator.comparing(PetExpress::getStateTime).reversed()).collect(Collectors.toList());
    }

    @Override
    public List<PetExpress> selectByDeliveryId(Integer id) {
        return lambdaQuery().eq(PetExpress::getDeliveryId, id).orderByDesc(PetExpress::getStateTime).list();
    }

    @Override
    public int add(PetExpress petExpress) {
        return baseMapper.insert(petExpress);
    }

    @Override
    public int deleteById(Integer id) {
        return baseMapper.deleteById(id);
    }

}
